//
// Created by Zxy on 2020/9/6.
//

#ifndef UNIONFIND_UNIONFIND3_H
#define UNIONFIND_UNIONFIND3_H

#include <cassert>
class UnionFind3 {
private:
    int *parent;
    int *sz;
    int count;
public:
    UnionFind3(int count){
        this->count = count;
        parent = new int[count];
        sz = new int[count];
        for(int i = 0; i < count; i++) {
            parent[i] = i;
            sz[i] = 1;
        }
    }
    ~UnionFind3(){
        delete [] parent;
        delete [] sz;
    }
    int find(int p){
        assert(p >= 0 && p < count);
        // 寻找根节点，复杂度O(n)
        while(p != parent[p])
            p = parent[p];
        return p;
    }
    bool isConnected(int p, int q){
        return find(p) == find(q);
    }
    void unionElements(int p, int q){
        int pRoot = find(p);
        int qRoot = find(q);
        if(pRoot == qRoot) return;
        // 基于size优化
        if(sz[pRoot] < sz[qRoot]){
            parent[pRoot] = qRoot;
            sz[qRoot] += sz[pRoot];
        }
        else{
            parent[qRoot] = pRoot;
            sz[pRoot] += sz[qRoot];
        }
    }
};
#endif //UNIONFIND_UNIONFIND3_H
